/*
 ** writen by hanv
 ** n2.vietha@gmail.com
 */
package vn.vng.research.fsd.data;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.lucene.index.IndexReader;
import org.apache.lucene.search.Collector;
import org.apache.lucene.search.FieldCache;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.Scorer;

import vn.vng.research.fsd.da.SchoolRefinerDA;
import vn.vng.research.fsd.services.thrift.TSchool;
import vn.vng.research.fsd.services.thrift.TUser;

public class FacetCollector extends Collector {
	FacetedTopDocs topDocs = new FacetedTopDocs();
	private Map<Integer, Integer> schoolIndex = new HashMap<Integer, Integer>();
	private Scorer scorer;
	private int[] educations;
	private int docBase = 0;

	@Override
	public boolean acceptsDocsOutOfOrder() {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public void collect(int docID) {
		// TODO Auto-generated method stub

		try {
			
			ScoreDoc scoreDoc = new ScoreDoc(docID+docBase, scorer.score());
			topDocs.getScoreDocuments().add(scoreDoc);
			
			int education = educations[docID];
			Integer index = schoolIndex.get(education);


			if (education != SchoolRefinerDA.UNKNOWN_ID){
				if (index == null) {
					String name = SchoolRefinerDA.getSchoolName(education);
					int count = 1;
					TSchool newSchool = new TSchool(education, name, count);
	
					schoolIndex.put(education, topDocs.getSchoolLs().size());
					topDocs.getSchoolLs().add(newSchool);

				} else {
					TSchool oldSchool = topDocs.getSchoolLs().get(index);
					oldSchool.setCount(oldSchool.getCount() + 1);
				}
			}
			
			topDocs.setTotalHits(topDocs.getTotalHits()+1);
		} catch (Exception e) {
			// TODO: handle exception
		}

	}

	@Override
	public void setNextReader(IndexReader reader, int docBase)
			throws IOException {
		// TODO Auto-generated method stub
		educations = FieldCache.DEFAULT.getInts(reader, "education");
		this.docBase = docBase;

	}

	@Override
	public void setScorer(Scorer scorer) throws IOException {
		// TODO Auto-generated method stub
		this.scorer = scorer;
	}

	public FacetedTopDocs getTopDocs() {
		return topDocs;
	}



}
